package com.dycn.posdashboard.services.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.JobDetail;
import org.quartz.SchedulerException;

import com.dycn.posdashboard.dao.PosTransactionDataDao;
import com.dycn.posdashboard.data.Branch2MerchantMapping;
import com.dycn.posdashboard.data.MerchantInfo;
import com.dycn.posdashboard.data.PaginatedInfor;
import com.dycn.posdashboard.data.PosQueryResponseData2;
import com.dycn.posdashboard.data.PosResponseTransactionData;
import com.dycn.posdashboard.data.PosTransactionData;
import com.dycn.posdashboard.data.ServicesResultObject;
import com.dycn.posdashboard.dbhelper.DataBaseUser;
import com.dycn.posdashboard.job.PosTransactionDataSyncJob;
import com.dycn.posdashboard.listener.SystemInitListener;
import com.dycn.posdashboard.services.LiveTransactionDataServices;
import com.dycn.posdashboard.services.PosTradeServices;
import com.dycn.posdashboard.services.SyncTransactionDataServices;
import com.dycn.posdashboard.util.DataCacheUtils;
import com.dycn.posdashboard.util.HttpClientUtils;
import com.dycn.posdashboard.util.QuartzManager;

import cryptix.jce.provider.MD5;

public class SyncTransactionDataServicesImpl implements
		SyncTransactionDataServices {
    
	protected final Log log = LogFactory.getLog(getClass());
    
	private Cache systmDataCache;
	
	private PosTransactionDataDao posTransactionDataDao;
	private LiveTransactionDataServices liveTransactionDataServices;
	private PosTradeServices posTradeServices;
	
	public PosTradeServices getPosTradeServices() {
		return posTradeServices;
	}


	public void setPosTradeServices(PosTradeServices posTradeServices) {
		this.posTradeServices = posTradeServices;
	}


	public LiveTransactionDataServices getLiveTransactionDataServices() {
		return liveTransactionDataServices;
	}


	public void setLiveTransactionDataServices(
			LiveTransactionDataServices liveTransactionDataServices) {
		this.liveTransactionDataServices = liveTransactionDataServices;
	}


	public PosTransactionDataDao getPosTransactionDataDao() {
		return posTransactionDataDao;
	}


	public void setPosTransactionDataDao(PosTransactionDataDao posTransactionDataDao) {
		this.posTransactionDataDao = posTransactionDataDao;
	}


	public Cache getSystmDataCache() {
		return systmDataCache;
	}

	public void setSystmDataCache(Cache systmDataCache) {
		this.systmDataCache = systmDataCache;
	}
	
	
	public PaginatedInfor<PosTransactionData> getPosTransactionDataByHttp(String merchantNo,int pageId){
		PaginatedInfor<PosTransactionData> paginatedInfor=new PaginatedInfor<PosTransactionData>();
		paginatedInfor.setPageRecords(20);
		paginatedInfor.setPageId(pageId);
		
//		version 	网关接收支付请求接口版本	1 	不可空	固定值：1 
//		signType	签名类型 	2 	不可空	固定选择值：0、1、2
//		0代表不签名，仅供网关内部商户使用；1代表MD5加密签名方式；2代表证书方式 
//		reqSource	请求源	1	不可空	固定选择值：1、2、3
//		1--- web  2 --- POS  3 --- 手机
//		买卖双方信息参数
//		merchantNo	商户号 	15 	不可空 	数字串 本参数用来指定接收受理商户号 
//		terminalNo	终端号	8	不可空	数字串 本参数用来指定接收受理终端号
//		业务参数
//		cmId	商品代码 	2 	不可空	字符串 只允许使用数字-303
//		用于代表不同的网上业务
//		merNo	交易商户号 	15 	不可空 	数字串 本参数用来指定接收交易商户号 
//		terNo	交易终端号	8	可空	数字串 本参数用来指定接收交易终端号
//		cardNo	卡号	19	可空	字符串 只允许使用数字
//
//		tradeType	交易类型	3	不可空	字符串 只允许使用数字 ,用于代表交易类型
//		 01-POS消费，22- OTO-POS消费,31-POS取消,41-POS冲正
//		date	交易时间	10	可空	字符串 用于表示交易日期
//		pageNum	请求的页号	3	不可空	默认为1
//		signMsg	签名字符串 	1024 	不可空	以上所有非空参数及其值与密钥组合，经MD5后生成。签名转化为大写的32位字符串 
//			对于所有值不为空的参数值，按照如上顺序及如下规则组成字符串 参数1值参数2值„„参数n值key
//		签名方式：把上面的字符串进行MD5或证书签名后，转化为大写。
//		version 1
//		signType 1
//		reqSource 1
//		merchantNo 98000872
//		terminalNo 98000813
//		cmId 303
//		merNo 906290053110001
//		tradeType 01
//		pageNum 1
//		signMsg
//
//
//		signMsg：
//		密钥是123456
//		所有不为空的值拼接后 再拼上123456 然后再MD5一下,中间没有空格.
		
		//String requestURL=SystemInitListener.QUERYTRADE_POS_URL;
		//String requestURL="http://pay.sanwing.com/ws/business/queryTrade";
		String requestURL=SystemInitListener.QUERYTRADE_POS_URL;
		log.info("requestURL:"+requestURL);
		LinkedHashMap<String,Object> requestparams=new LinkedHashMap<String,Object>();

//		ServicesResultObject<Branch2MerchantMapping> branch2MerchantMappingData=posTradeServices.getBranch2MerchantMappingInfo(DataBaseUser.MAIN_USER);
//		Branch2MerchantMapping someBranch2MerchantMapping=branch2MerchantMappingData.getReturnObj();
//		MerchantInfo requestMerchantInfo=someBranch2MerchantMapping.getMerchantInfoByMerchantNo(merchantNo);
		
		String requestBranchNo="98000872";
		//requestBranchNo=requestMerchantInfo.getBranchNo();
		String serviceProviderNo="98000872";
		String serviceProviderName="大银财富";
		
		requestparams.put("version", "1");
		requestparams.put("signType", "1");
		requestparams.put("reqSource", "1");
		requestparams.put("merchantNo", serviceProviderNo);//查询的总公司编号
		requestparams.put("terminalNo", "98000813");//8位 查询
		requestparams.put("cmId", "303");
		if(merchantNo!=null&&!merchantNo.trim().equals("")){
			requestparams.put("merNo", merchantNo);//商家号信息 
		}
		requestparams.put("tradeType", "01");//请求返回的的业务数据类型 01 pos消费
		requestparams.put("pageNum", String.valueOf(pageId));//
		requestparams.put("payFlag", "0");
		
		
		requestparams.put("signMsg", queryTradesRequestSign(requestparams));//
		
		List<PosTransactionData> remotePosTransactionDatas=new ArrayList<PosTransactionData>();
		
		try {
			String reponseContent=HttpClientUtils.postJsonBody(requestURL, requestparams, "UTF-8");
			JSONObject responseJsonObject = JSONObject.fromObject(reponseContent);
			//{"version":"1","signType":"1","reqSource":"1","merchantNo":"98000872","terminalNo":"98000813","cmId":"303","dataSize":"0","success":"true",
			//"dataResults":"[]","signMsg":"E689FA7F676337435A77BFF77481B0AA"}
			PosQueryResponseData2 somePosQueryResponseData=(PosQueryResponseData2)JSONObject.toBean(responseJsonObject, PosQueryResponseData2.class);
			System.out.println(somePosQueryResponseData.getDataResults());
			String dataResultArrayJson=somePosQueryResponseData.getDataResults().substring(1);
			dataResultArrayJson=dataResultArrayJson.substring(0,dataResultArrayJson.length()-1);
			//JSONArray.fromObject(dataResultArrayJson);
			
			List<PosResponseTransactionData> posResponseTransactionDataList=JSONArray.toList(JSONArray.fromObject(dataResultArrayJson), 
					PosResponseTransactionData.class);
			
			
			//PosQueryResponseData somePosQueryResponseData=(PosQueryResponseData)JSONObject.toBean(responseJsonObject, PosQueryResponseData.class);
			
			PosTransactionData soemPosTransactionData=null;
			for(PosResponseTransactionData somePosResponseTransactionData:posResponseTransactionDataList){
				//String merchantNoRes=somePosResponseTransactionData.getMerNo();//商家编号
				//somePosResponseTransactionData.getMerchantName();//分公司名
				
				soemPosTransactionData=new PosTransactionData();

				
				soemPosTransactionData.setCardNo(somePosResponseTransactionData.getCardNo());
				soemPosTransactionData.setCmId(Integer.parseInt(somePosQueryResponseData.getCmId()));
				soemPosTransactionData.setComments(somePosResponseTransactionData.getResponseComment());
				soemPosTransactionData.setCreateTime(new Date());
				soemPosTransactionData.setInOrderNo(somePosResponseTransactionData.getInOrderNo());
				
				//soemPosTransactionData.setTerminalMerchantName(someBranch2MerchantMapping.getMerchantInfoByMerchantNo(merchantNoRes).getMerchantName());//商户信息
				//soemPosTransactionData.setTerminalMerchantNo(merchantNo);
				soemPosTransactionData.setServiceProviderNo(serviceProviderNo);
				soemPosTransactionData.setServiceProviderName(serviceProviderName);
				soemPosTransactionData.setBranchName(somePosResponseTransactionData.getMerchantName());//分公司信息
				soemPosTransactionData.setBranchNo(somePosResponseTransactionData.getMerNo());
				
				soemPosTransactionData.setTerminalMerchantName(somePosResponseTransactionData.getTerminalName());
				soemPosTransactionData.setTerminalMerchantNo(somePosResponseTransactionData.getTerNo());
				
				soemPosTransactionData.setOldTerminalOrderNo(somePosResponseTransactionData.getOldTmOrderNo());
				soemPosTransactionData.setRtnOrderNo(somePosResponseTransactionData.getRtnOrderNo());
				soemPosTransactionData.setTerminalBatchNo(somePosResponseTransactionData.getTerBatchNo());

				soemPosTransactionData.setTerminalOrderNo(somePosResponseTransactionData.getTerNo());
				soemPosTransactionData.setTradeDate(somePosResponseTransactionData.getTradeDate1());
				soemPosTransactionData.setTradeFee(somePosResponseTransactionData.getTradeFee());
				soemPosTransactionData.setTradeMoney(somePosResponseTransactionData.getTradeMoney());
				soemPosTransactionData.setTradeOrderId(somePosResponseTransactionData.getTradeOrderId());
				soemPosTransactionData.setTradeType(somePosResponseTransactionData.getTradeType());
				
				remotePosTransactionDatas.add(soemPosTransactionData);
			}

			paginatedInfor.setTotalRecords(somePosQueryResponseData.getDataSize());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		
		//convert to javabean
		paginatedInfor.setDataList(remotePosTransactionDatas);
		
		return paginatedInfor;
	}
	
	/**
	 * 请求的数据加密方法
	 * @return
	 */
	private String queryTradesRequestSign(Map<String,Object> requestparams){
		String md5Key="123456";
		Iterator<String> iteratorKey=requestparams.keySet().iterator();
		StringBuffer singBuffer=new StringBuffer();
		while(iteratorKey.hasNext()){
			String key=iteratorKey.next();
			requestparams.get(key);
			singBuffer.append(requestparams.get(key));
		}
		MD5 md5=new MD5();
		String finalSign=md5.toMD5(singBuffer.append(md5Key).toString()).toUpperCase();
		//String finalSign=MD5Support.MD5(singBuffer.append(md5Key).toString()).toUpperCase();
		log.info("orgin queryTradesRequestSign:"+singBuffer.toString());
		log.info("final queryTradesRequestSign:"+finalSign);
		
		return finalSign;
	}
	
	private PaginatedInfor<PosTransactionData> syncTransactionWithRemotePOSSystemInternal(String merchantNo,int pageId) {
		//访问卡系统 via HttpClient

		//按定义个规则，返回的数据降序排列，也就是是最新的交易数据最新的数据排在最前面
		//每页最多20条数据
		PaginatedInfor<PosTransactionData> remotePosTransactionPaginatedInfor=getPosTransactionDataByHttp(merchantNo,pageId);
//		int totalRecords=remotePosTransactionPaginatedInfor.getTotalRecords();
//		int currentPageId=remotePosTransactionPaginatedInfor.getPageId();
//		int totalPage=remotePosTransactionPaginatedInfor.getTotalPage();
		List<PosTransactionData> remotePosTransactionDatas=remotePosTransactionPaginatedInfor.getDataList();

		Collections.sort(remotePosTransactionDatas, new Comparator<PosTransactionData>(){

			@Override
			public int compare(PosTransactionData arg0, PosTransactionData arg1) {
				// TODO Auto-generated method stub
				
				return arg0.getTradeDate().compareTo(arg1.getTradeDate())*-1;
			}
			
		});
		ServicesResultObject<Branch2MerchantMapping> branch2MerchantMappingServicesResultObject=posTradeServices.getBranch2MerchantMappingInfo(DataBaseUser.MAIN_USER);
		Branch2MerchantMapping someBranch2MerchantMapping=branch2MerchantMappingServicesResultObject.getReturnObj();
		
		
		//判断返回的数据列表中的第一条
		//当前商户的最新交易时间
		Date lastPosTransactionDataDate=this.getLastSyncDatetime(merchantNo);
		List<PosTransactionData> incrementPosTransactionDatas=new ArrayList<PosTransactionData>();
		//比较值延迟20毫秒
		long realLastDataLong=-1;
		for(PosTransactionData someRemotePosTransactionData:remotePosTransactionDatas){
			if(someRemotePosTransactionData.getTradeDate().compareTo(lastPosTransactionDataDate)>0){
				MerchantInfo someMerchantInfo=someBranch2MerchantMapping.getMerchantInfoByMerchantNo(someRemotePosTransactionData.getTerminalMerchantNo());
				if(someMerchantInfo!=null){
					someRemotePosTransactionData.setTerminalMerchantName(someMerchantInfo.getTerminalMerchantName());
					someRemotePosTransactionData.setBranchName(someMerchantInfo.getBranchName());
				}
				
				incrementPosTransactionDatas.add(someRemotePosTransactionData);
				//realLastData=someRemotePosTransactionData.getTradeDate();
				realLastDataLong=Math.max(lastPosTransactionDataDate.getTime(), someRemotePosTransactionData.getTradeDate().getTime());
			}else{
				//update lastDataLong
				//this.updateLastSyncDatetime(merchantNo, new Date(realLastDataLong));
				break;
			}
		}

		
		//返回数据
		List<PosTransactionData> insertResultList=this.posTransactionDataDao.batchInsertPosTransactionData(DataBaseUser.MAIN_USER, incrementPosTransactionDatas);
		if(insertResultList==null){
			//do update
			incrementPosTransactionDatas=this.posTransactionDataDao.batchUpdatePosTransactionData(DataBaseUser.MAIN_USER, incrementPosTransactionDatas);
		}
		
		if(incrementPosTransactionDatas!=null){
			//将数据缓存到本地缓存中，供实时查询功能使用
			liveTransactionDataServices.updateLastPosTransactionInforOnCache(incrementPosTransactionDatas);
			
			if(incrementPosTransactionDatas.size()<remotePosTransactionPaginatedInfor.getPageRecords()){
				//没有更新的数据或者没有更多的数据
				remotePosTransactionPaginatedInfor.setTotalRecords(-1);
			}
			remotePosTransactionPaginatedInfor.setDataList(incrementPosTransactionDatas);
			
			if(realLastDataLong>0){
				//this.updateLastSyncDatetime(merchantNo, new Date(realLastDataLong));	
			}
		}else{
			remotePosTransactionPaginatedInfor.setTotalRecords(-1);
		}

		return remotePosTransactionPaginatedInfor;
	}
	
	
	private PaginatedInfor<PosTransactionData> syncTransactionWithRemotePOSSystemInternalFirstPage(String merchantNo,int pageId) {
		//访问卡系统 via HttpClient

		//按定义个规则，返回的数据降序排列，也就是是最新的交易数据最新的数据排在最前面
		//每页最多20条数据
		PaginatedInfor<PosTransactionData> remotePosTransactionPaginatedInfor=getPosTransactionDataByHttp(merchantNo,pageId);
//		int totalRecords=remotePosTransactionPaginatedInfor.getTotalRecords();
//		int currentPageId=remotePosTransactionPaginatedInfor.getPageId();
//		int totalPage=remotePosTransactionPaginatedInfor.getTotalPage();
	
		List<PosTransactionData> remotePosTransactionDatas=remotePosTransactionPaginatedInfor.getDataList();

		Collections.sort(remotePosTransactionDatas, new Comparator<PosTransactionData>(){

			@Override
			public int compare(PosTransactionData arg0, PosTransactionData arg1) {
				// TODO Auto-generated method stub
				
				return arg0.getTradeDate().compareTo(arg1.getTradeDate())*-1;
			}
			
		});
		
		ServicesResultObject<Branch2MerchantMapping> branch2MerchantMappingServicesResultObject=posTradeServices.getBranch2MerchantMappingInfo(DataBaseUser.MAIN_USER);
		Branch2MerchantMapping someBranch2MerchantMapping=branch2MerchantMappingServicesResultObject.getReturnObj();
		
		
		//判断返回的数据列表中的第一条
		//当前商户的最新交易时间
		Date lastPosTransactionDataDate=this.getLastSyncDatetime(merchantNo);
		List<PosTransactionData> incrementPosTransactionDatas=new ArrayList<PosTransactionData>();
		//比较值延迟20毫秒
		long realLastDataLong=-1;
		for(PosTransactionData someRemotePosTransactionData:remotePosTransactionDatas){
			if(someRemotePosTransactionData.getTradeDate().compareTo(lastPosTransactionDataDate)>0){
				MerchantInfo someMerchantInfo=someBranch2MerchantMapping.getMerchantInfoByMerchantNo(someRemotePosTransactionData.getTerminalMerchantNo());
				if(someMerchantInfo!=null){
					someRemotePosTransactionData.setTerminalMerchantName(someMerchantInfo.getTerminalMerchantName());
					someRemotePosTransactionData.setBranchName(someMerchantInfo.getBranchName());
				}
				incrementPosTransactionDatas.add(someRemotePosTransactionData);
				//realLastData=someRemotePosTransactionData.getTradeDate();
				realLastDataLong=Math.max(lastPosTransactionDataDate.getTime(), someRemotePosTransactionData.getTradeDate().getTime());
			}else{
				//update lastDataLong
				//this.updateLastSyncDatetime(merchantNo, new Date(realLastDataLong));
				break;
			}
		}


		
		//返回数据
		List<PosTransactionData> insertResultList=this.posTransactionDataDao.batchInsertPosTransactionData(DataBaseUser.MAIN_USER, incrementPosTransactionDatas);
		if(insertResultList==null){
			//do update
			incrementPosTransactionDatas=this.posTransactionDataDao.batchUpdatePosTransactionData(DataBaseUser.MAIN_USER, incrementPosTransactionDatas);
		}
		
		if(incrementPosTransactionDatas!=null){
			//将数据缓存到本地缓存中，供实时查询功能使用
			liveTransactionDataServices.updateLastPosTransactionInforOnCache(incrementPosTransactionDatas);
			
			if(incrementPosTransactionDatas.size()<remotePosTransactionPaginatedInfor.getPageRecords()){
				//没有更新的数据或者没有更多的数据
				remotePosTransactionPaginatedInfor.setTotalRecords(-1);
			}
			remotePosTransactionPaginatedInfor.setDataList(incrementPosTransactionDatas);
			
			if(realLastDataLong>0){
				//this.updateLastSyncDatetime(merchantNo, new Date(realLastDataLong));	
			}
		}else{
			remotePosTransactionPaginatedInfor.setTotalRecords(-1);
		}

		return remotePosTransactionPaginatedInfor;
	}
	
	@Override
	public void syncTransactionWithRemotePOSSystem(String merchantNo) {
		// TODO Auto-generated method stub
		//访问卡系统 via HttpClient

		//按定义个规则，返回的数据降序排列，也就是是最新的交易数据最新的数据排在最前面
		PaginatedInfor<PosTransactionData> remotePosTransactionPaginatedInfor=syncTransactionWithRemotePOSSystemInternalFirstPage(merchantNo,1);
		//int totalRecords=remotePosTransactionPaginatedInfor.getTotalRecords();
		int currentPageId=remotePosTransactionPaginatedInfor.getPageId();
		int totalPage=remotePosTransactionPaginatedInfor.getTotalPage();
		
		long realLastDataLong=0;
		Date lastPosTransactionDataDate=this.getLastSyncDatetime(merchantNo);
		
		realLastDataLong=getMaxDateFromTransactionList(remotePosTransactionPaginatedInfor.getDataList(),lastPosTransactionDataDate.getTime());
		
		for(int i=currentPageId+1;i<=totalPage;i++){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			remotePosTransactionPaginatedInfor=syncTransactionWithRemotePOSSystemInternal(merchantNo,i);

			realLastDataLong=getMaxDateFromTransactionList(remotePosTransactionPaginatedInfor.getDataList(),realLastDataLong);
			
			
			log.info("requestURL:"+new Date(realLastDataLong));
		}

		if(realLastDataLong>0){
			this.updateLastSyncDatetime(merchantNo, new Date(realLastDataLong));	
		}
	
		
	}
	
	
	public long getMaxDateFromTransactionList(List<PosTransactionData> tradesList,long lastPosTransactionDataDate){
		
		long maxTranscateDate=0;
		Collections.sort(tradesList, new Comparator<PosTransactionData>(){

			@Override
			public int compare(PosTransactionData arg0, PosTransactionData arg1) {
				// TODO Auto-generated method stub
				
				return arg0.getTradeDate().compareTo(arg1.getTradeDate())*-1;
			}
			
		});
	
		if(tradesList!=null&&tradesList.size()!=0){
			//realLastDataLong=Math.max(tradesList.get(0).getTradeDate().getTime(), lastPosTransactionDataDate.getTime());
			maxTranscateDate=Math.max(tradesList.get(0).getTradeDate().getTime(), lastPosTransactionDataDate);
		}else{
			maxTranscateDate=lastPosTransactionDataDate;
		}
		
		return maxTranscateDate;
	}



	@Override
	public Date getLastSyncDatetime(String merchantNo) {
		// TODO Auto-generated method stub
		Element lastSyncTimeElement=systmDataCache.get(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA);
		if(lastSyncTimeElement==null){
			lastSyncTimeElement=new Element(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA,new HashMap<String,Date>());
			systmDataCache.put(lastSyncTimeElement);
		}
		Map<String,Date> syncDatMap=(Map<String,Date>)lastSyncTimeElement.getValue();
		
		if(syncDatMap.get(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA)==null){
	        try{
		         FileReader read = new FileReader(new File(getClass().getResource("/").getFile()+"../../lastsync")); 
		         StringBuffer sb = new StringBuffer(); 
		         char ch[] = new char[1024]; 
		         int d = read.read(ch); 
		         while(d!=-1){ 
			         String str = new String(ch,0,d); 
			         sb.append(str); 
			         d = read.read(ch); 
		         }
		         System.out.print(sb.toString());
		         SimpleDateFormat myFmt=new SimpleDateFormat("yyyyMMddHHmmss");
		         Date lastSyncDate=myFmt.parse(sb.toString());

		        syncDatMap.put(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA, lastSyncDate);
		        read.close();
	        } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				syncDatMap.put(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA, DateUtils.addMilliseconds(new Date(), -20));
			}finally{
				
			}
		}


		if(merchantNo==null||merchantNo.trim().equals("")){
			return syncDatMap.get(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA);
		}else{
			if(syncDatMap.get(merchantNo)==null){
				syncDatMap.put(merchantNo, DateUtils.addMilliseconds(new Date(), -20));
			}
		}
		return syncDatMap.get(merchantNo);
	}
	
	/**
	 * 
	 * @param merchantNo
	 */
	public void updateLastSyncDatetime(String merchantNo,Date lastSyncDate){
		try {
			Element lastSyncTimeElement=systmDataCache.get(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA);
			if(lastSyncTimeElement==null){
				lastSyncTimeElement=new Element(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA,new HashMap<String,Date>());
				systmDataCache.put(lastSyncTimeElement);
			}
			Map<String,Date> syncDatMap=(Map<String,Date>)lastSyncTimeElement.getValue();
			if(merchantNo==null||merchantNo.trim().equals("")){
				File file = new File(getClass().getResource("/").getFile()
						+ "../../lastsync");
				if (file.exists()) {
					file.delete();
				}
				file.createNewFile();
				BufferedWriter output = new BufferedWriter(new FileWriter(file));
		         SimpleDateFormat myFmt=new SimpleDateFormat("yyyyMMddHHmmss");
		         String lastSyncDateStr=myFmt.format(lastSyncDate);
				output.write(lastSyncDateStr);
				output.close();
				
				syncDatMap.put(DataCacheUtils.LAST_SYNC_TIME_OF_POSTRADE_DATA, lastSyncDate);
			}
			syncDatMap.put(merchantNo, lastSyncDate);
		} catch (Exception ex) {
			System.out.println(ex);
		}

	}


	@Override
	public void startPosDataSyncJob() {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		//0 0/2 * * * ? 每2分钟执行一次
        try {
			JobDetail jobDetail = new JobDetail("syncPosTranscationJob-同步POS交易数据JOB", "pos_trads_sync", new PosTransactionDataSyncJob().getClass());//任务名，任务组，任务执行类
			jobDetail.getJobDataMap().put("syncTransactionDataServices", this);
			//jobDetail.getJobDataMap().put("dbType", dbType);
			QuartzManager.getInstance().addJob(jobDetail,SystemInitListener.SYNC_POS_TRADE_QUARTZ);
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
